﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace P
{
    /// <summary>
    /// 时间帮助类
    /// </summary>
    public class TimeHelper
    {
        /// <summary>
        /// 获取网络时间
        /// </summary>
        /// <param name="isBeiJing">是否得到北京时间</param>
        /// <returns></returns>
        public static async Task<DateTime> GetTime(bool isBeiJing = false)
        {
            DateTime time = new System.DateTime(1970, 1, 1);
            HttpClient client = new HttpClient();
            try
            {
                var responseString = await client.GetStringAsync("https://time.weather.gov.hk/cgi-bin/time5a.pr?a=1");
                Console.WriteLine("从https://time.weather.gov.hk/cgi-bin/time5a.pr?a=1获取时间1970.1.1至现在的毫秒数成功毫秒为---", responseString.Substring(2));
                long lTime = long.Parse(responseString.Substring(2));
                //如果是北京时间，需要加上8个小时的时差
                if (isBeiJing)
                {
                    return time.AddMilliseconds(lTime).AddHours(8);
                }
                return time.AddMilliseconds(lTime);
            }
            catch(Exception)
            {
                Console.WriteLine("未知错误,返回 DateTime.UtcNow");
                if (isBeiJing)
                {
                    return DateTime.UtcNow.AddHours(8);
                }
                return DateTime.UtcNow;
            }
        }

        private static DateTime _DateTimeNow;
        /// <summary>
        /// 调用此方法开始自己维护的DateTime.Now，需要对此类的Timer赋值才能得到实时的DateTime
        /// </summary>
        /// <param name="time">默认null表示获取网络时间</param>
        public async static void MyDateTimeNow(DateTime? time = null)
        {
            if (time == null)
            {
                time=await GetTime(true);
            }
            Stopwatch sw1 = new Stopwatch();
            _DateTimeNow = (DateTime)time;
            sw1.Start();
            bool b = true;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int i = 1;
            while (true)
            {
                await Task.Delay(100);
                if (sw.ElapsedTicks / (decimal)Stopwatch.Frequency >= i)
                {
                    i++;
                    _DateTimeNow = _DateTimeNow.AddSeconds(1);
                    if (b)
                    {
                        b = false;
                        _DateTimeNow = _DateTimeNow.AddSeconds((double)(sw1.ElapsedTicks / (decimal)Stopwatch.Frequency));
                        sw1.Stop();
                    }
                    if (Timer != null)
                    {
                        Timer(_DateTimeNow);
                    }
                    //防止整型溢出
                    if (i ==int.MaxValue)
                    {
                        i = 0;
                        sw.Restart();
                    }
                    //Console.WriteLine(_DateTimeNow.ToString("HH:mm:ss"));
                }
            }
        }
        /// <summary>
        /// 委托，参数就是实时时间
        /// </summary>
        public static Action<DateTime> Timer;
    }
}
